package com.aratek.salary.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.MailParseException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.time.LocalDateTime;

/**
 * @author Yvan Jiang
 * @version 0.0.1
 * @Title MailService
 * @note 邮件发送服务
 * @note Copyright 2016 by Aratek . All rights reserved
 * @time 2017/11/16
 **/
@Service
public class MailService {
    
    static {
        System.setProperty("mail.mime.splitlongparameters","false");
    }
    
    @Autowired
    JavaMailSender mailSender;
    
    @Autowired
    private MailProperties mailProperties;
    private final Logger LOG = LoggerFactory.getLogger(MailService.class);
    
    public void sendEmail(String email,File part){
        LOG.info("开始发送{}的邮件",email);
        MimeMessage message = mailSender.createMimeMessage();
        try{
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(email);
            helper.setSubject("【工资单】"+(LocalDateTime.now().minusMonths(1).getMonthValue()) + "月工资条，请注意查收并保密");
            String text = "您好，\n\n    附件是您"+(LocalDateTime.now().minusMonths(1).getMonthValue()) +"月工资的工资条。请注意查收。\n\n    谢谢。" +
                    "\n\n\n\n\n"+
                    "PS: 该邮件是系统自动发送邮件，请您不要直接回复该邮箱。\n"+
                    "=======================\n"+
                    "Power by Software R & D\n"+
                    "=======================\n";
            helper.setText(text);
            LOG.debug(part.getName());
            if(part.getName().split("_").length == 2) {
                helper.addAttachment(part.getName().split("_")[1], part);
            }else {
                helper.addAttachment(part.getName(),part);
            }
        }catch (MessagingException e) {
            throw new MailParseException(e);
        }
        mailSender.send(message);
        LOG.info("发送{}的邮件完成",email);
    }
}
